#!/usr/bin/env python


import xmltodict
import gzip

def parse_attrib ( node, keys ):
	res = {}

	def _get_val ( n, mode, name ):
		if mode == "s":
			return n [ 'dia:string' ] [ 1 : -1 ]
		elif mode == "c":
			if 'dia:composite' in n:
				return  n [ 'dia:composite' ]

		return None

	my_keys = {}
	for k in keys:
		mode, name = k.split ( ":" )
		my_keys [ name ] = mode

	for n in node:
		name = n [ "@name" ]
		if name in my_keys:
			val = _get_val ( n, my_keys [ name ], name )
			if val:
				res [ name ] = val

	return res

class DiaClass ( object ):
	def __init__ ( self, elem ):
		self.elem = elem

		self.id = elem [ '@id' ]
		self._parse ()

	def _parse ( self ):
		#
		# s = string, c = composite
		res = parse_attrib ( self.elem [ 'dia:attribute' ], [ "s:name", "s:comment", "c:attributes" ] )
		self.props = []
		self.attrs = res

		if not 'attributes' in res: return

		attribs = res [ 'attributes' ]
		del self.attrs [ 'attributes' ]

		if not isinstance ( attribs, list ): attribs = [ attribs ]

		for attr in attribs:
			self.props.append ( parse_attrib ( attr [ 'dia:attribute' ], [ "s:name", "s:type", "s:value", "s:comment" ] ) )
			

class DiaCodeGen ( object ):
	def __init__ ( self ):
		self.tree = None
		self.classes = {}

	def load ( self, fname ):
		self.tree = xmltodict.parse ( gzip.open ( fname ).read () )
		self.tree = self.tree.get ( "dia:diagram", {} )

	def parse ( self ):
		self._objs ()
		
	def dump ( self ):
		import json

		print  json.dumps ( self.tree, indent = 2 )

	def _objs ( self ):
		objs = self.tree [ 'dia:layer' ] [ 'dia:object' ]
		for obj in objs:
			if obj [ '@type' ] == 'UML - Class':
				o = DiaClass ( obj )
				self.classes [ o.id ] = o

		print self.classes


if __name__ == '__main__':
	fname = "work/example.dia"

	dcg = DiaCodeGen ()
	dcg.load ( fname )
	#dcg.dump ()
	dcg.parse ()
	
	print "======================================"
	print dcg.classes [ 'O0' ].attrs
	print "======================================"
	print dcg.classes [ 'O0' ].props

	
